<?php
declare (strict_types = 1);

namespace app\middleware;
use think\Request;

class IntranetAccessIpMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        if ($request->ip() === '127.0.0.1') return $next($request);

        $ips    = config('app.intranet_access_ip');
        $ip     = explode('.', $request->ip());
        $access = false;
        foreach($ips as $index => $ip2){
            $arr = explode('.', $ip2);
            if (4 > count($arr) || 4 > count($ip)) break;
            // 只匹配 ip 地址的前三部分（192.168.0）
            if ($arr[0] === $ip[0] && $arr[1] === $ip[1] && $arr[2] === $ip[2])
            {
                $access = true;
                break;
            }
        }
        if ($access === false) return json(['code' => 0, 'message' => "此路不通"]);

        return $next($request);
    }
}
